package com.zaofan.service.remote;

import com.google.common.reflect.TypeToken;
import com.zaofan.bean.Account;
import com.zaofan.bean.CouponUser;
import com.zaofan.bean.OrderInfo;
import com.zaofan.bean.QualityExtend;
import com.zaofan.constant.UrlConstant;
import com.zaofan.exception.ServiceException;
import com.zaofan.mobile.bean.ProductResultV2;
import com.zaofan.utils.GsonUtils;
import com.zaofan.utils.HTTPClient;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RemoteService {
	
	private static final Logger logger = LoggerFactory.getLogger(RemoteService.class);
	
	/**
	 * 首页展示的周套餐接口url
	 */
	private static final String M_ZHOUTAOCAN_URL = UrlConstant.HOST_URL + "/m/index/zhoutaocan";
	
	private static final String M_QRCODE_RECORD_USER = UrlConstant.HOST_URL + "/m/QRCode/record/user";
	
	private static final String M_QRCODE_OPENID_USER = UrlConstant.HOST_URL + "/m/QRCode/record/openid/user";
	
	private static final String BOSS_ZHOUTAOCAN_ADD_URL = UrlConstant.HOST_URL + "/boss/product/zhoutaocan/add";
	
	private static final String BOSS_ZHOUTAOCAN_UPDATE_URL = UrlConstant.HOST_URL + "/boss/product/zhoutaocan/update";
	
	private static final String BOSS_ZHOUTAOCAN_GET_URL = UrlConstant.HOST_URL + "/boss/product/zhoutaocan/get";

	private static final String M_QRCODE_NEW_USER  = UrlConstant.HOST_URL + "/m/QRCode/NewUser";

	private static final String M_QRCODE_NEW_ORDER  = UrlConstant.HOST_URL + "/m/QRCode/NewOrder";

	private static final String M_QRCODE_NEW_USERORDER  = UrlConstant.HOST_URL + "/m/QRCode/NewUserOrder";

	private static final String M_COUPON_LOCK = UrlConstant.HOST_URL + "/m/Coupon/lockCoupon";

	private static final String M_COUPON_PAY = UrlConstant.HOST_URL + "/m/Coupon/useCoupon";

	private static final String M_COUPON_BACK = UrlConstant.HOST_URL+"/m/Coupon/backCouponTimeOut";

	/**
	 * 获取首页展示的周套餐数据
	 * 
	 * @return null if not norm
	 */
	public List<ProductResultV2> getZhouTaoCan(Integer cityId) {
		Map<String, String> map = new HashMap<>();
		map.put("cityId", String.valueOf(cityId));
		String result = HTTPClient.postMap(M_ZHOUTAOCAN_URL, map);
		if (result == null) {
			return null;
		}
		 ObjectMapper mapper = new ObjectMapper();
         JsonNode json;
		try {
			json = mapper.readTree(result);
	        if (json != null && json.has("success") && json.get("success").asBoolean() == true && json.has("data")) {
	        	return GsonUtils.getInstance().fromJson(json.get("data").toString(), new TypeToken<List<ProductResultV2>>() {
	        		private static final long serialVersionUID = 1L;
	        	}.getType());
	        }
		} catch (IOException e) {
			e.printStackTrace();
		}
         return null;
	}

	public void addQualityExtend(QualityExtend qualityExtend, Integer cityId, Integer productId) {
		Map<String, String> map = new HashMap<>();
		map.put("cityId", String.valueOf(cityId));
		map.put("productId", String.valueOf(productId));
		map.put("sendDate", qualityExtend.getSendDate());
		map.put("image", qualityExtend.getQualityimage());
		map.put("bigImage", qualityExtend.getQualitybigImage());
		map.put("timeoutImage", qualityExtend.getQualitytimeOutImage());
		String result = HTTPClient.postMap(BOSS_ZHOUTAOCAN_ADD_URL, map);
		if (result == null) {
			throw new RuntimeException("添加精品（周套餐）商品额外属性， 发生 异常");
		}
		 ObjectMapper mapper = new ObjectMapper();
         JsonNode json;
		try {
			json = mapper.readTree(result);
	        if (json != null && json.has("success") && json.get("success").asBoolean() == true) {
	        	return ;
	        }
		} catch (IOException e) {
			throw new RuntimeException("添加精品（周套餐）商品额外属性， 发生 异常");
		}
		throw new RuntimeException("添加精品（周套餐）商品额外属性， 发生 异常");
	}

	public void updateQualityExtend(QualityExtend qualityExtend, Integer cityId, Integer productId) {
		Map<String, String> map = new HashMap<>();
		map.put("cityId", String.valueOf(cityId));
		map.put("productId", String.valueOf(productId));
		map.put("sendDate", qualityExtend.getSendDate());
		map.put("image", qualityExtend.getQualityimage());
		map.put("bigImage", qualityExtend.getQualitybigImage());
		map.put("timeoutImage", qualityExtend.getQualitytimeOutImage());
		String result = HTTPClient.postMap(BOSS_ZHOUTAOCAN_UPDATE_URL, map);
		if (result == null) {
			throw new RuntimeException("更新精品（周套餐）商品额外属性， 发生 异常");
		}
		 ObjectMapper mapper = new ObjectMapper();
         JsonNode json;
		try {
			json = mapper.readTree(result);
	        if (json != null && json.has("success") && json.get("success").asBoolean() == true) {
	        	return ;
	        }
		} catch (IOException e) {
			throw new RuntimeException("更新精品（周套餐）商品额外属性， 发生 异常");
		}
		throw new RuntimeException("更新精品（周套餐）商品额外属性， 发生 异常");
	}

	public QualityExtend getQualityExtend(Long productId) {
		Map<String, String> map = new HashMap<>();
		map.put("productId", String.valueOf(productId));
		String result = HTTPClient.postMap(BOSS_ZHOUTAOCAN_GET_URL, map);
		if (result == null) {
			throw new RuntimeException("获取精品（周套餐）商品额外属性， 发生 异常");
		}
		 ObjectMapper mapper = new ObjectMapper();
         JsonNode json;
		try {
			json = mapper.readTree(result);
	        if (json != null && json.has("success") && json.get("success").asBoolean() == true && json.has("data")) {
	        	QualityExtend qualityExtend = new QualityExtend();
	        	qualityExtend.setQualitybigImage(json.get("data").get("bigImage").asText());
	        	qualityExtend.setQualityimage(json.get("data").get("image").asText());
	        	qualityExtend.setQualitytimeOutImage(json.get("data").get("timeoutImage").asText());
	        	qualityExtend.setSendDate(json.get("data").get("sendDate").asText());
	        	return qualityExtend;
	        }
		} catch (IOException e) {
			e.printStackTrace();
		}
		throw new RuntimeException("获取精品（周套餐）商品额外属性， 发生 异常");
	}

	public void recordQRCodeId(String QRCodeId, Account user) {
		logger.info("QRCodeId: {}, user: {}", QRCodeId, user.getMobile());
		if (StringUtils.isBlank(QRCodeId) || StringUtils.isBlank(user.getMobile())) {
			return;
		}
		Map<String, String> map = new HashMap<>();
		map.put("QRCodeId", QRCodeId);
		map.put("userPhone", user.getMobile());
		HTTPClient.postMap(M_QRCODE_RECORD_USER, map);
	}

	public void qrCode(String openid, String userPhone, int userId) {
		logger.info("openid: {}, user: {}", openid, userPhone);
		if (StringUtils.isBlank(openid) 
				|| "null".equals(openid)
				|| StringUtils.isBlank(userPhone)) {
			return;
		}
		Map<String, String> map = new HashMap<>();
		map.put("openid", openid);
		map.put("userPhone", userPhone);
		map.put("userId", String.valueOf(userId));
		HTTPClient.postMap(M_QRCODE_OPENID_USER, map);
	}

	public List<Account> NewUser(String qr_code_desc, String orderTime,String builderId){
		Map<String, String> map = new HashMap<>();
		map.put("qr_code_desc",qr_code_desc);
		map.put("orderTime",orderTime);
		map.put("builderId",builderId);

		String result = HTTPClient.postMap(M_QRCODE_NEW_USER, map);
		if (result == null) {
			return null;
		}
		System.out.println("------------------------"+result);
		ObjectMapper mapper = new ObjectMapper();
		JsonNode json;
		try {
			json = mapper.readTree(result);
			if (json != null && json.has("success") && json.get("success").asBoolean() == true && json.has("data")) {
				return GsonUtils.getInstance().fromJson(json.get("data").toString(), new TypeToken<List<Account>>() {
					private static final long serialVersionUID = 1L;
				}.getType());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;



	}

	public List<OrderInfo> NewOrder(String qr_code_desc, String orderTime,String builderId){
		Map<String, String> map = new HashMap<>();
		map.put("qr_code_desc",qr_code_desc);
		map.put("orderTime",orderTime);
		map.put("builderId",builderId);

		String result = HTTPClient.postMap(M_QRCODE_NEW_ORDER, map);
		if (result == null) {
			return null;
		}
		System.out.println("------------------------"+result);
		ObjectMapper mapper = new ObjectMapper();
		JsonNode json;
		try {
			json = mapper.readTree(result);
			if (json != null && json.has("success") && json.get("success").asBoolean() == true && json.has("data")) {
				return GsonUtils.getInstance().fromJson(json.get("data").toString(), new TypeToken<List<OrderInfo>>() {
					private static final long serialVersionUID = 1L;
				}.getType());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;



	}

	public CouponUser LockCoupon(BigDecimal totalprice, int userid, Long couponUserId, Integer couponId){
		Map<String, String> map = new HashMap<>();
		map.put("totalprice",totalprice.toString());
		map.put("userid",userid+"");
		map.put("couponUserId",couponUserId.toString());
		map.put("couponId",couponId.toString());
		String result = HTTPClient.postMap(M_COUPON_LOCK,map);
		if (result == null){
			return null;
		}
		System.out.println("250------------------------"+result);
		ObjectMapper mapper = new ObjectMapper();
		JsonNode json;
		try {
			json = mapper.readTree(result);
			if (json != null && json.has("success") && json.get("success").asBoolean() == true && json.has("data")) {
				return GsonUtils.getInstance().fromJson(json.get("data").toString(), new TypeToken<CouponUser>() {
					private static final long serialVersionUID = 1L;
				}.getType());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void updateCouponStatus(String OrderNo) throws ServiceException {
		Map<String, String> map = new HashMap<>();
		map.put("OrderNo",OrderNo);

		String result = HTTPClient.postMap(M_COUPON_PAY,map);
		if (result == null){
			throw new ServiceException("支付使用优惠券失败");
		}
		System.out.println("------------------------"+result);
		ObjectMapper mapper = new ObjectMapper();
		JsonNode json;
		try {
			json = mapper.readTree(result);
			if (json != null && json.has("success") && json.get("success").asBoolean() == true) {
				logger.info("支付使用优惠券成功");
			}else{
				throw new ServiceException("支付使用优惠券失败");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
//		return null;
	}


	public List<OrderInfo> NewUserOrder(String qr_code_desc, String orderTime,String builderId){
		Map<String, String> map = new HashMap<>();
		map.put("qr_code_desc",qr_code_desc);
		map.put("orderTime",orderTime);
		map.put("builderId",builderId);

		String result = HTTPClient.postMap(M_QRCODE_NEW_USERORDER, map);
		if (result == null) {
			return null;
		}

		ObjectMapper mapper = new ObjectMapper();
		JsonNode json;
		try {
			json = mapper.readTree(result);
			if (json != null && json.has("success") && json.get("success").asBoolean() == true && json.has("data")) {
				return GsonUtils.getInstance().fromJson(json.get("data").toString(), new TypeToken<List<OrderInfo>>() {
					private static final long serialVersionUID = 1L;
				}.getType());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void backCouponTimeout(long delayTime){
		Map<String, String> map = new HashMap<>();
		map.put("delayTime",delayTime+"");
		HTTPClient.postMap(M_COUPON_BACK, map);
	}
}
